package com.compass.doctor.ui.patient

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.os.Bundle
import android.webkit.SslErrorHandler
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.viewModels
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.callback.OnCustomItemClick
import com.compass.doctor.databinding.ActivityRxExamineBinding
import com.compass.doctor.dialog.RxRejectDialog
import com.compass.doctor.ui.prescription.viewmodel.PrescribeViewModel
import com.compass.framework.R
import com.compass.framework.constant.KEY_ORDER_ID
import com.compass.framework.constant.KEY_RX_TYPE
import com.compass.framework.constant.KEY_TITLE
import com.compass.framework.constant.KEY_URL
import com.compass.framework.constant.REFRESH_RX
import com.compass.framework.constant.REFRESH_RX_EXAMINE
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.onClick
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.getStringFromResource


/**
 * Description： 处方审核
 * Date:2024/3/1 9:59
 */
class WebRXExamineActivity : BaseVBActivity<ActivityRxExamineBinding>() {
    private var mTitle = ""
    private var prescriptionId: String? = null
    private var rxType: Int? = 0 // 0处方审核 1.续费申请

    private val prescribeViewModel: PrescribeViewModel by viewModels()

    companion object {
        fun start(context: Context, url: String, title: String, id: String, rxType: Int) {
            val intent = Intent(context, WebRXExamineActivity::class.java)
            intent.putExtra(KEY_URL, url)
            intent.putExtra(KEY_TITLE, title)
            intent.putExtra(KEY_ORDER_ID, id)
            intent.putExtra(KEY_RX_TYPE, rxType)
            context.startActivity(intent)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        initWebView()
    }

    private fun initWebView() {
        mBinding.webView.webChromeClient = mWebChromeClient
        mBinding.webView.webViewClient = mWebViewClient //如果不设置则跳系统浏览器
    }

    override fun initData() {
        val url = intent?.getStringExtra(KEY_URL)
        mTitle = intent?.getStringExtra(KEY_TITLE) ?: ""
        prescriptionId = intent?.getStringExtra(KEY_ORDER_ID)
        rxType = intent?.getIntExtra(KEY_RX_TYPE, 0)
        showLoading()
        url?.let { mBinding.webView.loadUrl(it) }
        prescribeViewModel.examineLiveData.observe(this) {
            dismissLoading()
            if (it) {
                LiveDataBus.get().with(REFRESH_RX_EXAMINE).postValue(REFRESH_RX_EXAMINE)
                finish()
            }
        }


        prescribeViewModel.refuseLiveData.observe(this) {
            if (it) {
                LiveDataBus.get().with(REFRESH_RX_EXAMINE).postValue(REFRESH_RX_EXAMINE)
                finish()
            }

        }
    }

    private var onItemClick = object : OnCustomItemClick {
        override fun onItemCallBack(position: Int, orderId: String, suggest: String) {
            showLoading()
            prescribeViewModel.prescriptionExamine(orderId, "2", suggest)
        }


    }


    override fun intListener() {
        mBinding.tvUnPass.onClick {

            if (rxType == 0) {
                //审核拒绝
                prescriptionId?.let {
                    RxRejectDialog.Builder(this, it, onItemClick).show()
                }
            }
            if (rxType == 1) {
                //续访拒绝
                prescriptionRefuse()
            }

        }

        mBinding.tvPass.onClick {
            prescriptionAgree()
        }

    }


    /**
     * 续方--拒绝
     */
    private fun prescriptionRefuse() {
        CommonMessageDialog.Builder(this)
            .setTitle(getStringFromResource(R.string.dialog_tips_title))
            .setMessage("是否确认拒绝当前续方？")
            .setConfirm(getStringFromResource(R.string.default_confirm))

            .setCancel(getString(R.string.default_cancel))
            .setonCancelListener {
                it?.dismiss()
            }
            .setonConfirmListener {
                showLoading()
                prescriptionId?.let { id ->
                    prescribeViewModel.prescriptionRenewal(id, "0")
                }

                it?.dismiss()
            }.create().show()
    }


    /**
     * 审核处方--同意
     */
    private fun prescriptionAgree() {
        CommonMessageDialog.Builder(this)
            .setTitle(getStringFromResource(R.string.dialog_tips_title))
            .setMessage("是否确认通过当前处方？")
            .setConfirm(getStringFromResource(R.string.default_confirm))

            .setCancel(getString(R.string.default_cancel))
            .setonCancelListener {
                it?.dismiss()
            }
            .setonConfirmListener {

                prescriptionId?.let { id ->
                    showLoading()
                    if (rxType == 0) {
                        //审核同意
                        prescribeViewModel.prescriptionExamine(id, "1")
                    }
                    if (rxType == 1) {
                        //续访同意
                        prescribeViewModel.prescriptionRenewal(id, "1")
                    }
                }

                it?.dismiss()
            }.create().show()
    }


    /**
     * 辅助 WebView 处理 Javascript 的对话框,网站图标,网站标题等等
     */
    private val mWebChromeClient = object : WebChromeClient() {
        /**
         * 网页Title更改
         */
        override fun onReceivedTitle(webView: WebView?, title: String?) {
            super.onReceivedTitle(webView, title)
            if (webView != null && !webView.canGoBack() && mTitle.isNotEmpty()) {
                mBinding.titleBar.setMiddleText(mTitle)
            } else {
                var titleResult = ""
                if (!title.isNullOrEmpty() && !title.startsWith("http", true)) {
                    titleResult = title
                }
                mBinding.titleBar.setMiddleText(titleResult)
            }
        }

        /**
         * 文件选择回调
         */
        override fun onShowFileChooser(
            webView: WebView?,
            back: ValueCallback<Array<Uri>>?,
            chooser: FileChooserParams?
        ): Boolean {
            return super.onShowFileChooser(webView, back, chooser)
        }

        /**
         * 获得网页的加载进度并显示
         */
        override fun onProgressChanged(webView: WebView?, process: Int) {
            super.onProgressChanged(webView, process)
            if (process == 100) {
                dismissLoading()
            }
        }
    }

    /**
     * 处理各种通知 & 请求事件
     */
    private val mWebViewClient = object : WebViewClient() {
        /**
         * 网页加载完毕
         */
        override fun onPageFinished(webView: WebView?, url: String?) {
            super.onPageFinished(webView, url)
        }

        /**
         * 跳转拦截处理
         * 打开网页时，不调用系统浏览器进行打开，而是在本WebView中直接显示
         */
        override fun shouldOverrideUrlLoading(webview: WebView?, url: String?): Boolean {
            //处理url
            //mBinding.webView.loadUrl(url)
            return super.shouldOverrideUrlLoading(webview, url)
        }

        /**
         * 设置错误页面
         */
        override fun onReceivedError(webview: WebView?, p1: Int, p2: String?, p3: String?) {
            super.onReceivedError(webview, p1, p2, p3)
        }

        override fun onReceivedSslError(
            webView: WebView?,
            handler: SslErrorHandler?,
            error: SslError?
        ) {
            super.onReceivedSslError(webView, handler, error)
            //忽略ssl错误
            handler?.proceed()
        }
    }

    override fun onBackPressed() {
        if (mBinding.webView.canGoBack()) {
            mBinding.webView.goBack() // 返回上一个浏览页
        } else {
            super.onBackPressed()
        }
    }
}